package com.example.simin_manage.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.simin_manage.entity.PerformanceRule;
import com.example.simin_manage.mapper.PerformanceRuleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @description:
 * @author: panpan
 * @time: 2025/9/20
 */
@Service
public class PerformanceRuleService {

    @Autowired
    private PerformanceRuleMapper ruleMapper;

    // 保存规则
    public void saveRules(Long cycleId, List<PerformanceRule> rules) {
        // 先清空旧规则
        ruleMapper.delete(new QueryWrapper<PerformanceRule>().eq("cycle_id", cycleId));
        // 保存新规则
        LocalDateTime now = LocalDateTime.now();
        for (PerformanceRule r : rules) {
            r.setCycleId(cycleId);
            r.setCreateTime(now);
            r.setUpdateTime(now);
            ruleMapper.insert(r);
        }
    }

    // 查询某周期的规则
    public List<PerformanceRule> getRules(Long cycleId) {
        return ruleMapper.selectList(new QueryWrapper<PerformanceRule>()
                .eq("cycle_id", cycleId)
                .orderByAsc("min_orders"));
    }

    // 计算薪资
    public BigDecimal calculateSalary(Long cycleId, int orders) {
        List<PerformanceRule> rules = getRules(cycleId); // 按 min 升序
        BigDecimal total = BigDecimal.ZERO;

        if (orders < 100) {
            System.out.printf("总单数: %d 小于100单，不计薪%n", orders);
            return total;
        }

        for (PerformanceRule r : rules) {
            int min = r.getMinOrders();
            int max = r.getMaxOrders() == null ? Integer.MAX_VALUE : r.getMaxOrders();
            BigDecimal price = BigDecimal.valueOf(r.getPricePerOrder());

            int applicable;
            // 首个有效区间
            if (min < 100) {
                applicable = Math.min(orders, max);
            } else {
                if (orders <= min) continue; // 还没到这个区间
                applicable = Math.min(orders, max) - min;
            }

            if (applicable > 0) {
                BigDecimal tierSalary = price.multiply(BigDecimal.valueOf(applicable));
                total = total.add(tierSalary);

                System.out.printf("[区间 %d-%s单] 单价 ¥%.2f, 计薪订单 %d 单, 金额 ¥%.2f%n",
                        min,
                        max == Integer.MAX_VALUE ? "以上" : max,
                        r.getPricePerOrder(),
                        applicable,
                        tierSalary
                );
            }
        }

        System.out.printf("总薪资: ¥%.2f%n", total);
        return total;
    }




}
